package com.ants.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * TODO
 * Author Chen
 * Date   2022/8/26 14:11
 */
@Slf4j
public class ImageUtil {

    /**
     *
     * @param inputStream           文件流
     * @param waterMarkContent      水印文字
     * @return
     */
    public static InputStream watermarkImg(InputStream inputStream, String waterMarkContent) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            //将文件流对象转化为图片对象
            Image srcImg = ImageIO.read(inputStream);
            //获取图片的宽
            int srcImgWidth = srcImg.getWidth(null);
            //获取图片的高
            int srcImgHeight = srcImg.getHeight(null);

            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            // 加水印
            //创建画笔
            Graphics2D g = bufImg.createGraphics();
            //绘制原始图片
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            //-------------------------文字水印 start----------------------------
            //根据图片的背景设置水印颜色
            int fontSize = 60;
            g.setFont(new Font("微软雅黑", Font.BOLD, 60));
            //设置水印的坐标(为原图片中间位置)
            int x = (srcImgWidth - getWatermarkLength(waterMarkContent, g) - 100);
            int y = srcImgHeight - fontSize - 50;
            //画出水印 第一个参数是水印内容，第二个参数是x轴坐标，第三个参数是y轴坐标
            g.drawString(waterMarkContent, x, y);
            g.dispose();
            //-------------------------文字水印 end----------------------------

            // 输出图片
            ImageIO.write(bufImg, "jpg", os);
        } catch (Exception e) {
            // 失败 原流返回
            return inputStream;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new ByteArrayInputStream(os.toByteArray());
    }

    public static void main(String[] args) throws IOException {
        // 读取原图片信息 得到文件（本地图片）
        File srcImgFile = new File("C:\\Users\\LX\\Pictures\\微信图片_20200717161454.jpg");
        //将文件对象转化为图片对象
        Image srcImg = ImageIO.read(srcImgFile);
        //获取图片的宽
        int srcImgWidth = srcImg.getWidth(null);
        //获取图片的高
        int srcImgHeight = srcImg.getHeight(null);
        System.out.println("图片的宽:" + srcImgWidth);
        System.out.println("图片的高:" + srcImgHeight);

        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        // 加水印
        //创建画笔
        Graphics2D g = bufImg.createGraphics();
        //绘制原始图片
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        //-------------------------文字水印 start----------------------------
//        //根据图片的背景设置水印颜色
        g.setColor(new Color(255, 255, 255, 198));
        //设置字体  画笔字体样式为微软雅黑，加粗，文字大小为60pt
        int fontSize = 60;
        g.setFont(new Font("微软雅黑", Font.BOLD, 60));
        String waterMarkContent = "june·12  chenshuang";
        //设置水印的坐标(为原图片中间位置)
        int x = (srcImgWidth - getWatermarkLength(waterMarkContent, g) - 100);
        int y = srcImgHeight - fontSize - 50;
        //画出水印 第一个参数是水印内容，第二个参数是x轴坐标，第三个参数是y轴坐标
        g.drawString(waterMarkContent, x, y);
        g.dispose();
        //-------------------------文字水印 end----------------------------

        //-------------------------图片水印 start----------------------------
        // 水印文件
//        String waterMarkImage="D:\\s.jpg";
//        Image srcWaterMark = ImageIO.read(new File(waterMarkImage));
//        //获取水印图片的宽度
//        int widthWaterMark= srcWaterMark.getWidth(null);
//        //获取水印图片的高度
//        int heightWaterMark = srcWaterMark.getHeight(null);
//        //设置 alpha 透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
//        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
//        //绘制水印图片  坐标为中间位置
//        g.drawImage(srcWaterMark, (srcImgWidth - widthWaterMark) / 2,
//                (srcImgHeight - heightWaterMark) / 2, widthWaterMark, heightWaterMark, null);
//        // 水印文件结束
//        g.dispose();
        //-------------------------图片水印 end----------------------------

        //待存储的地址
        String tarImgPath = "D:\\t.png";
        // 输出图片
        FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
        ImageIO.write(bufImg, "jpg", outImgStream);
        System.out.println("添加水印完成");
        outImgStream.flush();
        outImgStream.close();

    }

    /**
     * 获取水印文字的长度
     *
     * @param waterMarkContent
     * @param g
     * @return
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

    /**
     * 对图片进行原比例无损压缩,压缩后覆盖原图片
     *
     * @param path
     * @return
     */
    public static InputStream doWithPhoto(InputStream inputStream) {

        BufferedImage image = null;
//        FileOutputStream os = null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            image = ImageIO.read(inputStream);
            int width = image.getWidth();
            int height = image.getHeight();
            BufferedImage bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bfImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
//            os = new FileOutputStream(path);

            ImageIO.write(bfImage, "jpg", os);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new ByteArrayInputStream(os.toByteArray());
    }

    public static List<String> getImgSrc(String htmlStr) {
        String img = "";
        Pattern p_image;
        Matcher m_image;
        List<String> pics = new ArrayList<>();
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }


}
